import request from "@/utils/request.js";

const PREFIX = '/user/order'

import {getCartItems, getCheckout} from "@/api/cart.js";

// 结算相关 API

// 获取运费
export const getShippingFee = async (addressId) => {
    await new Promise(resolve => setTimeout(resolve, 300))
    return 0 // 免运费
}

// 创建订单
export const createOrder = async (data) => {
    await new Promise(resolve => setTimeout(resolve, 500))
    const {items, addressId} = data

    // 生成订单号
    const orderNo = 'XJM' + Date.now()

    // 计算总金额
    const totalAmount = items.reduce((sum, item) => sum + item.product.price * item.quantity, 0)

    // 创建新订单
    const newOrder = {
        orderNo,
        status: 'pending',
        totalAmount,
        addressId,
        orderItems: items.map(item => ({
            productId: item.product.id,
            productName: item.product.name,
            price: item.product.price,
            quantity: item.quantity,
            productImage: item.product.image,
            isReviewed: 0
        })),
    }
    return request.post(PREFIX, newOrder);
}

// 获取订单确认页信息
export const getCheckoutInfo = async (cartItemIds) => {
    const {data: items} = await getCheckout(cartItemIds)
    return {
        items,
        totalAmount: items.reduce((sum, item) => sum + item.price * item.quantity, 0),
        shippingFee: 0
    }
}
